package com.base.self.common;

import cn.hutool.core.date.DateUtil;
import com.base.result.ResponseResultUtils;
import com.base.self.entity.Commodity;
import com.base.self.entity.SelfOrder;
import com.base.self.mapper.CommodityMapper;
import com.base.self.mapper.SelfOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author XiFYuW
 * @since  2020/10/10 12:07
 */
@Service
@Slf4j
public class LockStockService {

    private final CommodityMapper commodityMapper;

    private final ReadWriteLock stockLock;

    private final SelfOrderMapper selfOrderMapper;

    public LockStockService(CommodityMapper commodityMapper, SelfOrderMapper selfOrderMapper) {
        this.commodityMapper = commodityMapper;
        this.selfOrderMapper = selfOrderMapper;
        this.stockLock = new ReentrantReadWriteLock();
    }

    /*拼团扣库存*/
    public void updateStockPartaker(final Integer id, final SelfOrder selfOrder){
        stockLock.writeLock().lock();
        try {
            final Commodity commodity = commodityMapper.selectById(id);
            final Integer stock = commodity.getCommodityStock() - selfOrder.getNumber();
            selfOrder.setOrderNumber(commodity.getCommoditySales() + 1);
            selfOrderMapper.updateById(selfOrder);
            if (stock > 0) {
                commodity.setCommodityStock(stock);
                commodity.setCommoditySales(commodity.getCommoditySales() + 1);
                commodity.setUpdateTime(DateUtil.date());
                commodityMapper.updateById(commodity);
            } else {
                log.warn("库存：{}", stock);
            }
        }finally {
            stockLock.writeLock().unlock();
        }
    }

    /*兑换扣库存*/
    public void updateStockConversion(final Integer id, final Integer tradeNumber){
        stockLock.writeLock().lock();
        try {
            final Commodity commodity = commodityMapper.selectById(id);
            final Integer stock = commodity.getCommodityStock() - tradeNumber;
            if (stock.compareTo(0) < 0) {
                throw new SelfRuntimeException(ResponseResultUtils.getResponseResultF("库存不足"));
            }
            commodity.setCommodityStock(stock);
            commodity.setCommoditySales(commodity.getCommoditySales() + 1);
            commodity.setUpdateTime(DateUtil.date());
            commodityMapper.updateById(commodity);

        }finally {
            stockLock.writeLock().unlock();
        }
    }
}
